/*
 *  Copy and edit from http://blog.raffaeu.com/archive/2010/06/26/how-to-write-fluent-interface-with-c-and-lambda.aspx
 */

namespace Cik.Gapi4Net.Core.FluentInterface
{
    using System;
    using System.Linq.Expressions;
    using System.Reflection;

    public class GenericFactory<T> : IGenericFactory<T>
    {
        private T _entity;

        public GenericFactory(T entity)
        {
            _entity = entity;
        }

        public IGenericFactory<T> With(Expression<Func<T, object>> property, object value)
        {
            PropertyInfo propertyInfo = null;

            if (property.Body is MemberExpression)
            {
                propertyInfo = ((MemberExpression)property.Body).Member as PropertyInfo;
            }
            else
            {
                propertyInfo = ((MemberExpression)((UnaryExpression)property.Body).Operand).Member as PropertyInfo;
            }

            propertyInfo.SetValue(_entity, value, null);

            return this;
        }

        public T Create()
        {
            return _entity;
        }
    }
}